
function BondMarket_DataManager(){
	
}

BondMarket_DataManager.prototype={
	TreasuryYieldsUrl:"../invoke/getTreasuryYields",
	GovtBondUrl:"../invoke/getUSGovtBond",
	loadTreasuryData:function(callback){
//		var data = {};
        $.get(this.TreasuryYieldsUrl,callback);
	},
	
	loadUSGovtData:function(callback){
//		var data = {};
        $.get(this.GovtBondUrl,callback);
	}
}


var gBondMarket_DataManager=new BondMarket_DataManager();


function BondMarket(container,cfg){
	this.$container=(typeof container)=="string" ? $("#"+container) : container;

	this.cfg={
		w:this.$container.width()||400,
		h:this.$container.height()||300,
		defaultMenuId:0
	}
	$.extend(true,this.cfg,cfg);
	this.lang=QS_Lang.marketBond;
	this.$container.css({width:this.cfg.w,height:this.cfg.h});
	this.init();
}

BondMarket.prototype={
	init:function(){
		//init dom
		var lang=this.lang;

		this.$container.append('<div class="bondmarket">'+
									'<div class="bm-tabmenuwrap">'+
										'<div class="bm-tabmenu"></div>'+
									'</div>'+
								'</div>');
								
		//init menu
		var tabData = [ {txt: lang['treasuryyield'],id: 1,closable: false}, 
						{txt: lang['usgovbond'],id: 2,closable: false}, 
						{txt: '10 '+lang['year']+' '+lang['tnoteyield'],id: 3,closable: false}];
						
		this.$tabMenu=this.$container.find(".bm-tabmenu");
		var tabMenu = new Util.TabMenu(this.$tabMenu[0], tabData, {}, {
//			width: 80,
//			tabsList: false,
//			rearrange: true,
			needTitle:true
		});
		var contentData=[{
			gridHead:{rowName:lang['maturity'], valName:lang['pyield']},
			gridData:[	{name:'6 '+lang['month'],val:""},
						{name:'2 '+lang['year'],val:""},
						{name:'5 '+lang['year'],val:""},
						{name:'10 '+lang['year'],val:""},
						{name:'30 '+lang['year'],val:""}],
			chartHead:{left:lang['oneyearago'],right:lang['lastclose']},
//			imageSrc:"https://tools.morningstar.com/new_home_page/home_page_image.aspx?type=BC_3MONTH|BC_6MONTH|BC_2YEAR|BC_5YEAR|BC_10YEAR|BC_30YEAR&ago=TODAY|BC_1YEAR&width=245&height=118",
			footerText:lang['dataasoflastclose']
		},{
			gridHead:{rowName:lang['msindex'], valName:lang['value']},
			gridData:[	{name:lang['usgov'],val:""},
						{name:lang['shortusgov'],val:""},
						{name:lang['midusgov'],val:""},
						{name:lang['longusgov'],val:""}],
			chartHead:{left:lang['usgovbond']},
			imageSrc:"http://tools.morningstar.com/new_home_page/home_page_image.aspx?type=BMK&ticker=FOUSA06IEX&CountryId=USA&ExchangeId=&TimePeriod=M1",
			footerText:lang['dataasoflastclose']
		},{
			gridHead:{rowName:lang['maturity'], valName:lang['pyield']},
			gridData:[	{name:'6 '+lang['month'],val:""},
						{name:'2 '+lang['year'],val:""},
						{name:'5 '+lang['year'],val:""},
						{name:'10 '+lang['year'],val:""},
						{name:'30 '+lang['year'],val:""}],
			chartHead:{left:'6 '+lang['month']+' '+lang['noteyield']},
			imageSrc:"http://tools.morningstar.com/new_home_page/home_page_image.aspx?type=BC_30YEAR",
			footerText:lang['dataasoflastclose']
		}];
		
		contentTemplate='<div class="bm-content-wrap">'+
							'<div class="bm-content-grid-wrap">'+
								'{{#gridHead}}'+
									'<div class="bm-gridhead-row"><span>{{rowName}}</span><span>{{valName}}</span></div>'+
								'{{/gridHead}}'+
								'<div class="bm-gridbody">'+
									'{{#gridData}}'+
										'<div class="bm-grid-row"><span>{{name}}</span><span class="bm-grid-value">{{val}}</span></div>'+	
									'{{/gridData}}'+
								'</div>'+
							'</div>'+
							'<div class="bm-content-chart-wrap">'+
								'<div class="bm-chart-title-wrap">'+
									'<span>{{chartHead.left}}</span><span>{{chartHead.right}}</span>'+
								'</div>'+
								'<div class="bm-chart-main-wrap">'+
									'{{#imageSrc}}'+
										'<img src="{{imageSrc}}"/>'+
									'{{/imageSrc}}'+
								'</div>'+
							'</div>'+
							'<div class="bm-content-footer">{{footerText}}</div>'+
						'</div>';
		
		
		
		for(var i=0;i<tabMenu.tabs.length;i++){
			tabMenu.tabs[i].panel.append(Mustache.render(contentTemplate,contentData[i]));
		}
		
		this.$contentWrap = this.$container.find('.bm-content-wrap');
		this.$contentGridWrap = this.$contentWrap.find('.bm-content-grid-wrap');
		this.$contentChartWrap = this.$contentWrap.find('.bm-content-chart-wrap');
			
		this.$chartTitleWrap = this.$contentChartWrap.find('.bm-chart-title-wrap');
		var $tab1Title=this.$chartTitleWrap.first().find('span');
		$tab1Title.eq(0).addClass('bm-charthead-year');
		$tab1Title.eq(1).addClass('bm-charthead-close');
		
		this.chartTitleH=this.$chartTitleWrap.height();
		this.footerH = this.$contentWrap.find('.bm-content-footer').outerHeight(true);
		
		this.$imgsCtn = this.$contentChartWrap.find('.bm-chart-main-wrap');
		//fix second img text
		this.$fixOneMonth=$('<div class="bm-fix-onemonth">'+lang['onemonth']+'</div>').appendTo(this.$imgsCtn.eq(1));
		
		this.$imgs = this.$imgsCtn.find("img");
		
		this.$gridBody = this.$contentGridWrap.find('.bm-gridbody');
		this.$gridBody.eq(1).addClass('bm-grid-hover');
		this.$gridBody.eq(2).addClass('bm-grid-hover');
		
		this._bindEvent();
		
		this.bmChart = new BondMarketLineChart(this.$imgsCtn.first(),{});

		this.loadData();
		this.changeOutSize(this.cfg.w, this.cfg.h);
	},
	loadData:function(){
		var self = this;
		gBondMarket_DataManager.loadTreasuryData(function(data){
			if(data&&data!="error"){
				var jData = $.evalJSON(data);
				jData&&self._updateData(jData);
			}
		})
		
		gBondMarket_DataManager.loadUSGovtData(function(data){
			if(data&&data!="error"){
				var jData = $.evalJSON(data);
				jData&&self._updateData(jData);
			}
		})
	},
	_updateData:function(jData){
		var lang=this.lang;
		if(jData.treasurys && jData.treasurys.length){
			var tData=jData.treasurys;
			var chartData=this.convertData(tData);
			chartData[0].lineOption={color:'#1B2064'};
			chartData[1].lineOption={color:'#F19620'};
			for(var i in tData){
				var d=tData[i];
				if(d.ClosePrice1Day){
					d.fixedPrice=parseFloat(d.ClosePrice1Day).toFixed(2);//fix float number
//					jData.treasurys[i].tansName=lang[jData.treasurys[i].ticker];//show tanslated language
				}
			}
			this.bmChart.init(chartData);
			tData.shift();//del 3 month
			
			this.updataGridValue(this.$gridBody.eq(0).find('.bm-grid-row .bm-grid-value'),tData);
			this.updataGridValue(this.$gridBody.eq(2).find('.bm-grid-row .bm-grid-value'),tData);
			
		}else if(jData.bonds && jData.bonds.length){
			var bData=jData.bonds;
			for(var i in bData){
				if(bData[i].LastPrice){
//					bData[i].name=bData[i].name.slice(3,-5);//
					bData[i].fixedPrice=parseFloat(bData[i].LastPrice).toFixed(2);
				}
			}

			this.updataGridValue(this.$gridBody.eq(1).find('.bm-grid-row .bm-grid-value'),bData);
		}
		
	},
	updataGridValue:function($cells, data){
		$cells.each(function(i){
			if(data[i].fixedPrice){
				$(this).html(data[i].fixedPrice);
			}
		});
	},
	convertData:function(treasurys){
		var chartData=[];
		var lineD={data:[],xTick:[]};
		var lineY={data:[],xTick:[]};
		for(var i=0;i<treasurys.length;i++){
			var t=treasurys[i];
			if(t.ClosePrice1Day){
				lineD.data.push([i,parseFloat(t.ClosePrice1Day)]);
				t.ticker&&lineD.xTick.push(parseInt(t.ticker));
			}
			if(t.ClosePrice1Year){
				lineY.data.push([i,parseFloat(t.ClosePrice1Year)]);
				t.ticker&&lineY.xTick.push(parseInt(t.ticker));
			}
		}
		chartData[0]=lineD;
		chartData[1]=lineY;
		return chartData;
	},
	changeOutSize:function(w,h){
		var self=this;
		w=Math.max(w,380);
		h=Math.max(h,200);
		this.cfg.w = w;
		this.cfg.h = h;
		this.$container.css({width:w,height:h});
		var contentH = h - 28;
		var contentW = w;
		this.$contentWrap.css({width:contentW, height:contentH});
		
		this.$contentGridWrap.css({height:contentH-this.footerH});
		this.$contentChartWrap.css({height:contentH-this.footerH});

		this.imgW = parseInt(contentW*0.64);
		this.imgH = parseInt(contentH-this.footerH - this.chartTitleH);

		this.$imgs.each(function(i){
			var metaData;
			if(i==0){
				metaData=self.metaMap().bonds;
			}else if(i==1){
				metaData=self.metaMap().treasurys;
			}
			self.changeImageSrc($(this), metaData.imgSrc[metaData.currentImg]);
		})

		this.bmChart.changeOutSize(this.imgW, this.imgH);
	},
	changeImageSrc:function($img, src){
		src += "&width="+this.imgW+"&height="+this.imgH;
		$img.attr("src", src);
	},
	_bindEvent:function(){
		var self=this;
		this.$gridBody.not(this.$gridBody.first()).find('.bm-grid-row').unbind().bind('mouseenter',function(e){
//			if(e.target.tagName != "SPAN")return;
			var $row=$(this);
			var $grid=$row.parent();
			var tabIndex=self.$gridBody.index($grid);
			var index=$grid.find(".bm-grid-row").index($row);
			var metaData;
			if(tabIndex==1){
				metaData=self.metaMap().bonds;
			}else if(tabIndex==2){
				metaData=self.metaMap().treasurys;
			}
			if(!metaData)return;
			self.$chartTitleWrap.eq(tabIndex).find('span:first').html(metaData.chartTitle[index]);
			self.changeImageSrc(self.$imgs.eq(tabIndex-1), metaData.imgSrc[index]);
			metaData.currentImg=index;
		});
	},
	metaMap:function(){
		var self=this;
		return {
			bonds:{
				currentImg:0,
				imgSrc:['http://tools.morningstar.com/new_home_page/home_page_image.aspx?type=BMK&ticker=FOUSA06IEX&CountryId=USA&ExchangeId=&TimePeriod=M1',
				'http://tools.morningstar.com/new_home_page/home_page_image.aspx?type=BMK&ticker=FOUSA06IF3&CountryId=USA&ExchangeId=&TimePeriod=M1',
				'http://tools.morningstar.com/new_home_page/home_page_image.aspx?type=BMK&ticker=FOUSA06IF5&CountryId=USA&ExchangeId=&TimePeriod=M1',
				'http://tools.morningstar.com/new_home_page/home_page_image.aspx?type=BMK&ticker=FOUSA06IF8&CountryId=USA&ExchangeId=&TimePeriod=M1'],
				chartTitle:[self.lang['usgov'],self.lang['shortusgov'],self.lang['midusgov'],self.lang['longusgov']]
			},
			treasurys:{
				currentImg:0,
				imgSrc:['http://tools.morningstar.com/new_home_page/home_page_image.aspx?type=BC_6MONTH',
						'http://tools.morningstar.com/new_home_page/home_page_image.aspx?type=BC_2YEAR',
						'http://tools.morningstar.com/new_home_page/home_page_image.aspx?type=BC_5YEAR',
						'http://tools.morningstar.com/new_home_page/home_page_image.aspx?type=BC_10YEAR',
						'http://tools.morningstar.com/new_home_page/home_page_image.aspx?type=BC_30YEAR'],
				chartTitle:['6 '+self.lang['month']+' '+self.lang['noteyield'],'2 '+self.lang['year']+' '+self.lang['noteyield'],'5 '+self.lang['year']+' '+self.lang['noteyield'],'10 '+self.lang['year']+' '+self.lang['noteyield'],'30 '+self.lang['year']+' '+self.lang['noteyield']]
			}
		}
	}
}